package com.dorm.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dorm.common.PageResult;
import com.dorm.common.Result;
import com.dorm.entity.Repair;
import com.dorm.service.RepairService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * 报修控制器
 */
@RestController
@RequestMapping("/repair")
public class RepairController {

    @Autowired
    private RepairService repairService;

    /**
     * 分页查询
     */
    @GetMapping("/page")
    public Result<PageResult<Repair>> page(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) Long studentId) {
        
        Page<Repair> page = repairService.pageQuery(pageNum, pageSize, status, studentId);
        PageResult<Repair> result = new PageResult<>(
                page.getRecords(),
                page.getTotal(),
                page.getCurrent(),
                page.getSize()
        );
        return Result.success(result);
    }

    /**
     * 根据ID查询
     */
    @GetMapping("/{id}")
    public Result<Repair> getById(@PathVariable Long id) {
        Repair repair = repairService.getById(id);
        return Result.success(repair);
    }

    /**
     * 新增
     */
    @PostMapping
    public Result<String> add(@RequestBody Repair repair) {
        repair.setStatus("待处理");
        repairService.save(repair);
        return Result.success("提交成功");
    }

    /**
     * 修改
     */
    @PutMapping
    public Result<String> update(@RequestBody Repair repair) {
        repairService.updateById(repair);
        return Result.success("修改成功");
    }

    /**
     * 分配维修人员
     */
    @PostMapping("/assign/{id}")
    public Result<String> assign(@PathVariable Long id, @RequestBody Repair repair) {
        Repair entity = repairService.getById(id);
        entity.setRepairman(repair.getRepairman());
        entity.setRepairmanPhone(repair.getRepairmanPhone());
        entity.setStatus("处理中");
        entity.setAssignTime(LocalDateTime.now());
        repairService.updateById(entity);
        return Result.success("分配成功");
    }

    /**
     * 完成报修
     */
    @PostMapping("/complete/{id}")
    public Result<String> complete(@PathVariable Long id, @RequestBody Repair repair) {
        Repair entity = repairService.getById(id);
        entity.setStatus("已完成");
        entity.setCompleteTime(LocalDateTime.now());
        entity.setRemark(repair.getRemark());
        repairService.updateById(entity);
        return Result.success("操作成功");
    }

    /**
     * 删除
     */
    @DeleteMapping("/{id}")
    public Result<String> delete(@PathVariable Long id) {
        repairService.removeById(id);
        return Result.success("删除成功");
    }
}

